# -*- coding: utf-8 -*-


import matplotlib.pyplot as plt
import sqlSearch


plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False


def solveAvg(result):
    avgResult = {}
    for i in result:
        zongshu = len(result[i])
        Sum = sum(result[i])
        avg = Sum / zongshu
        avg = int(avg)
        avgResult[i] = avg
    return avgResult

def autolabel(rects):
    for rect in rects:
        width = rect.get_width()
        heigth = rect.get_y()+0.25
        plt.text(width, heigth, width)

def solvePng(avgResult):
    fig, ax = plt.subplots()
    resultKey = []
    resultValue = []
    for i in avgResult:
        resultKey.append(i)
        resultValue.append(avgResult[i])

    bath = plt.barh(range(len(resultValue)), resultValue, tick_label=resultKey)
    autolabel(bath)


    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    plt.xlabel('价格')
    plt.ylabel('地区')
    plt.title('广州房价')
    plt.savefig('static/img/广州房价.png')

def solvePie(jinTwoYear,jinTwoFive,jinFiveTen,jinTenYear):
    labels = ['近两年', '二到五年', '五到十年', '十年以上']
    sizes = [jinTwoYear,jinTwoFive,jinFiveTen,jinTenYear]

    plt.pie(sizes, labels=labels, autopct='%1.1f%%')
    plt.title("广州商品房房龄分布")
    plt.savefig('static/img/广州商品房房龄分布.png')



result = {}
jinTwoYear = []
jinTwoFiveYear = []
jinFiveTenYear = []
jinTenYear = []

def chuTu():
    try:
        data = sqlSearch.searchAll()
        for i in data:
            fangDate = i['date']
            if fangDate != '暂无数据':
                fangDate = int(fangDate)
                if fangDate >= 2019:
                    jinTwoYear.append(fangDate)
                elif fangDate >= 2016 and fangDate <= 2018:
                    jinTwoFiveYear.append(fangDate)
                elif fangDate >= 2010 and fangDate <= 2015:
                    jinFiveTenYear.append(fangDate)
                else:
                    jinTenYear.append(fangDate)

            if result.get(i['address']):
                result[i['address']].append(i['price'])
            else:
                result[i['address']] = [i['price']]

        avgResult = solveAvg(result)

        solvePie(len(jinTwoYear), len(jinTwoFiveYear), len(jinFiveTenYear), len(jinTenYear))
        solvePng(avgResult)
        return True
    except Exception as e:
        print(e)
        return False

